import requests
import json
import os
import pymysql
import uuid
import time
import re


def createSql(data):
    pid = getPid()
    baseSql = 'INSERT INTO `wxapp_user`.`wxapp_menu` (`id`, `name`, `permission`, `pid`, `back_url`, `multi_url`, `order_num`, `icon`, `frame`, `menu_type`, `display`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `remark`) VALUES'
    path = os.path.dirname(__file__) + '/permission.sql'
    f = open(path, "w", encoding="utf-8")
    a = 0
    keys = []
    for k, v in data.items():
        key = k.replace('/', ':').lstrip(':')
        for k1, v1 in pid.items():
            if key.find(k1) != -1:
                if key not in keys:
                    keys.append(key)
                    a = a + 1
                    sql = baseSql + "('" + uuid.uuid1(
                    ).hex + "', '" + v + "', '" + key + "', " + v1 + ", '" + k + "', '', 1, 'Setting', 0, 'f', 1, 1, 1, '" + time.strftime(
                        '%Y-%m-%d %H:%M:%S',
                        time.localtime()) + "', NULL, NULL, '');\n"
                    f.write(sql)
    f.close()
    print("生成总共：" + str(a))


def getPid():
    connection = pymysql.connect(
        host='39.105.203.232',  # 数据库主机名
        port=3306,  # 数据库端口号，默认为3306
        user='remote_root',  # 数据库用户名
        passwd='wxapp_root_2022',  # 数据库密码
        db='wxapp_user',  # 数据库名称
        charset='utf8'  # 字符编码
    )
    cursor = connection.cursor()
    sql = "select id,permission from wxapp_menu where menu_type='c'"
    cursor.execute(sql)
    pid = {}
    for pi in cursor.fetchall():
        pid[pi[1]] = pi[0]
    return pid


if __name__ == "__main__":
    baseUrl = "http://localhost:6756"
    fristUrl = baseUrl + "/%s/v3/api-docs/%s?group=%s"
    services = [
        'admin', 'custom', 'dispatch', 'market', 'pay', 'sale', 'statistical',
        'system'
    ]
    # client = ['service', 'client', 'common']
    header = {'Authorization': 'Basic d3hhcHA6d3hhcHAxMjM='}
    list = {}
    a = 0
    # for cli in client:
    for ser in services:
        # urls = fristUrl % (ser, cli, cli)
        urls = fristUrl % (ser, 'service', 'service')
        data = json.loads(requests.get(url=urls, headers=header).text)
        if data.__contains__("error"):
            continue
        for k, v in data['paths'].items():
            name = ""
            if v.__contains__("put") and v["put"].__contains__("summary"):
                name = v["put"]["summary"]
            elif v.__contains__("get") and v["get"].__contains__("summary"):
                name = v["get"]["summary"]
            elif v.__contains__("post") and v["post"].__contains__("summary"):
                name = v["post"]["summary"]
            elif v.__contains__("delete") and v["delete"].__contains__(
                    "summary"):
                name = v["delete"]["summary"]
            pattern = r'\d+'  # 匹配一个或多个数字
            result = k
            if result.find("{") != -1:
                result = re.sub(r"\{.*?\}", "", result)[:-1]
            if name != '':
                list['/' + ser + result] = name
                a = a + 1
    print("总共接口：" + str(a))
    createSql(list)
